<template>
  <div class="external-treatment-container">
    <!-- 输液处方四 -->
    <div class="custom-table external-treatment-prescription">
      <!-- 标题栏 -->
      <div class="table-header" style="justify-content: space-between">
        <div style="display: flex; align-items: center">
          <div
            class="header-cell"
            style="width: 100px; color: #000000; font-weight: 600"
          >
            {{ transfusionTableData.rxName }}
          </div>
          <div style="margin-left: 15px">
            <el-select
              v-model="transfusionTableData.storageId"
              style="width: 140px"
              filterable
              class="borderless-select"
              @change="onStorage(transfusionTableData.groupList)"
              :disabled="
                visitStatus === '2' || transfusionTableData.payStatus == '2'
              "
            >
              <el-option
                v-for="frequency in storageList"
                :key="frequency.storageName"
                :label="frequency.storageName"
                :value="frequency.storageId"
              />
            </el-select>
          </div>
        </div>
        <div class="header-cell" v-if="visitStatus != '2'">
          <span style="color: #e37318; margin-right: 10px"
            >费用：￥{{
              (transfusionTableData.totalAmount / 100).toFixed(2)
            }}</span
          >
          <!-- <img
            src="@/assets/icon/icon_jiayizu_nor.svg"
            alt=""
            style="margin-right: 4px"
            v-if="transfusionTableData.payStatus != '2'"
          />
          <span
            v-if="transfusionTableData.payStatus != '2'"
            style="font-size: 12px; color: #16ada4; cursor: pointer"
            @click="addNewRow(1)"
            >加一组</span
          > -->
          <div
            style="
              width: 1px;
              height: 17px;
              background-color: #dcdcdc;
              margin: 0 4px;
            "
          ></div>
          <img
            v-if="transfusionTableData.payStatus != '2'"
            src="@/assets/manage/icon_del_nor.svg"
            alt=""
            style="cursor: pointer"
            @click="removeRow_1(transfusionTableData.groupList)"
          />
        </div>
      </div>

      <!-- 处方选择行 -->
      <template v-for="(tableData, index) in transfusionTableData.groupList">
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px;
          "
        >
          <div class="prescription-form-row">
            <div>{{ tableData.groupName }}</div>
            <div class="form-item">
              <div
                class="table-cell"
                @click.stop="onUsageCode(tableData)"
                v-if="
                  visitStatus !== '2' && transfusionTableData.payStatus != '2'
                "
                style="
                  width: 109px;
                  justify-content: flex-start;
                  padding-left: 8px;
                  position: relative;
                  height: 32px;
                  line-height: 32px;
                  border: 1px solid #dcdcdc;
                  border-radius: 4px;
                "
              >
                {{ tableData.usageCodeText }}
                <div
                  v-if="
                    showMedicationTabs &&
                    currentUsageRow.groupName === tableData.groupName
                  "
                  @click.stop
                  style="position: absolute; top: 30px; left: 0; z-index: 10"
                >
                  <MedicationTabs
                    @select="
                      (usage, usageName) =>
                        onSelect(tableData, usage, usageName)
                    "
                    :rxType="2"
                  />
                </div>
              </div>
              <span v-else style="padding: 0 20px">
                {{ tableData.usageCodeText }}
              </span>
            </div>
            <div class="form-item">
              <!-- <el-select
                v-model="tableData.frequencyCode"
                style="width: 100px"
                class="borderless-select"
                filterable
                :suffix-icon="CaretBottom"
                @change="onFrequency(tableData)"
                v-if="visitStatus !== '2'"
              >
                <el-option
                  v-for="frequency in frequency"
                  :key="frequency.frequencyCode"
                  :label="frequency.frequencyName"
                  :value="frequency.frequencyCode"
                />
              </el-select> -->

              <el-select
                v-model="tableData.frequencyCode"
                style="width: 120px"
                class="borderless-select"
                filterable
                :suffix-icon="CaretBottom"
                @focus="onfrequencyfocus"
                @change="onFrequency(tableData, tableData.frequencyCode)"
                v-if="
                  visitStatus !== '2' && transfusionTableData.payStatus != '2'
                "
              >
                <el-option
                  v-for="frequency in frequency"
                  :key="frequency.frequencyCode"
                  :label="frequency.frequencyName"
                  :value="frequency.frequencyCode"
                  style="padding: 0 8px"
                >
                  <span style="float: left">{{ frequency.frequencyCode }}</span>
                  <span style="float: right; font-size: 13px">
                    {{ frequency.frequencyName }}
                  </span>
                </el-option>
              </el-select>

              <span v-else style="padding: 0 20px">
                {{ tableData.frequencyCodeText }}
              </span>
            </div>
            <div class="form-item">
              <el-input-number
                v-model="tableData.cycle"
                :min="0"
                :max="999"
                :controls="false"
                class="borderless-input"
                style="width: 80px; height: 36px"
                @focus="showKeyboard(tableData, tableData.uuid, 'cycle')"
                @click.stop
                v-if="
                  visitStatus !== '2' && transfusionTableData.payStatus != '2'
                "
              />
              <span v-else>{{ tableData.cycle }}</span>
              <!-- 数字键盘 -->
              <div
                v-if="
                  keyboardVisible &&
                  isCurrentEditRow === tableData.uuid &&
                  currentEditField === 'cycle'
                "
                class="number-keyboard"
                @click.stop
              >
                <NumericKeyboardInt
                  @input="inputNumber"
                  @delete="deleteNumber"
                />
              </div>
            </div>

            <div class="form-item">
              <span class="unit-text">{{ tableData.cycleUnitText }}</span>
            </div>

            <div class="form-item">
              <!-- <el-input-number
                v-model="tableData.ivDripRate"
                :min="1"
                :max="999"
                :controls="false"
                class="borderless-input"
                style="width: 80px; height: 36px"
                @focus="showKeyboard(tableData, tableData.uuid, 'ivDripRate')"
                @click.stop
              /> -->
              <el-autocomplete
                v-model="tableData.ivDripRate"
                style="width: 70px"
                class="borderless-select center-input"
                placeholder="滴注"
                :trigger-on-focus="true"
                :fetch-suggestions="queryIvDripRateSuggestions"
                @select="(item) => onIvDripRateSelect(tableData, item)"
                v-if="
                  visitStatus !== '2' && transfusionTableData.payStatus != 2
                "
              />
              <!-- 数字键盘 -->
              <!-- <div
                v-if="
                  keyboardVisible &&
                  isCurrentEditRow === tableData.uuid &&
                  currentEditField === 'ivDripRate'
                "
                class="number-keyboard"
                @click.stop
              >
                <NumericKeyboard @input="inputNumber" @delete="deleteNumber" />
              </div> -->
              <span v-else>{{ tableData.ivDripRate }}</span>
            </div>
            <div class="form-item">
              <span class="unit-text">滴/分钟</span>
            </div>
          </div>
          <div
            class="header-cell"
            v-if="visitStatus !== '2' && transfusionTableData.payStatus != 2"
          >
            <span
              @click="addNewRow(2, tableData, index)"
              style="cursor: pointer"
            >
              <img
                src="@/assets/icon/icon_jiayizu_nor.svg"
                alt=""
                style="margin-right: 4px; vertical-align: middle"
                v-if="transfusionTableData.payStatus != '2'"
              />
              <span
                v-if="transfusionTableData.payStatus != '2'"
                style="font-size: 12px; color: #16ada4; vertical-align: middle"
                >加一组</span
              >
            </span>
            <div
              v-if="transfusionTableData.groupList.length > 1"
              style="
                width: 1px;
                height: 17px;
                background-color: #dcdcdc;
                margin: 0 4px;
              "
            ></div>
            <img
              src="@/assets/manage/icon_del_nor.svg"
              alt=""
              @click="removeRow(2, tableData)"
              style="cursor: pointer"
              v-if="transfusionTableData.groupList.length > 1"
            />
          </div>
        </div>

        <!-- 穴位选择区域 -->
        <div class="acupoint-selection-area">
          <transfusionTable
            ref="transfusionTableRef"
            title="查验项目"
            :tableData="tableData"
            :storageId="transfusionTableData.storageId"
            :frequencyOptions="frequency"
            :weight="prpops.weight"
            :payStatus="transfusionTableData.payStatus"
            :defaultActiveType="'inspection'"
            :onZS="onZS"
            :isInitialLoad="isInitialLoad"
            @isInitial="isInitial"
            :visitStatus="visitStatus"
            :displayNowUUid="displayNowUUid"
            :displayNowUUid2="displayNowUUid2"
            :displayNowUUid3="transfusionTableData.uuid"
            @searchKeyboard="onSearchKeyboard(tableData.uuid)"
            @update:tableData="
              (result: InspectionItem[]) => updateTableData(result, tableData)
            "
            @active-type-change="handleActiveTypeChange"
            @row-update="(row, idx) => updateRow(tableData, row, idx)"
            @search-result-select="
              (result) => handleSearchResultSelect(result, tableData)
            "
          />
        </div>
      </template>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import { CaretBottom, Star, Delete, Close } from '@element-plus/icons-vue';
import transfusionTable from './transfusionTable.vue';
import stores from '@/store';
import { getDrugRxList } from '@/api/formwork';
import { v4 as uuidv4 } from 'uuid';
import { calculateTotalDose, calculateAll } from '@/utils/rxUtil';
const useBaseData = stores.useBaseDataStore();
// 外治处方数据
const emits = defineEmits<{
  'update:tableData': [value: any[]];
  'active-type-change': [type: 'inspection' | 'examination'];
  'row-update': [row: any, index: number];
  'search-result-select': [result: any];
  addNewRow: [type: number, group?: any];
  removeRow: [value: any[]];
  searchKeyboard: any;
}>();
const keyboardVisible = ref(false);
const frequency = ref(useBaseData.getDictsSelect('FREQUENCY'));
const infusionIvDripRateEnum = ref(
  useBaseData.getEnumSelect('infusionIvDripRateEnum')
);
const isInitialLoad = ref(false);
const storageList = ref<any[]>(useBaseData.Storage);
const USAGE = ref(useBaseData.getDictsSelect('USAGE'));
const currentUsageRow = ref<any | null>(null);
const isCurrentEditRow = ref<any>(null);
const currentEditField = ref<any>(null);
const currentEditRow = ref<any | null>(null);
// 用法弹窗相关
const showMedicationTabs = ref<boolean>(false);
const externalTreatment = ref({
  medicineType: '小儿针灸套餐',
  dosage: '',
  frequency: '1日1次',
  remark: '',
  leftSide: '双',
  needleType: '速中',
  direction: '左',
  location: '太渊',
});
// 定义数据类型
interface InspectionItem {
  examId: number;
  name: string;
  category: '检验' | '检查';
  frequency: string;
  period: number;
  totalCount: number;
  remark: string;
  isNew?: boolean;
}
const activeType = ref<'inspection' | 'examination'>('inspection');
const dialogVisible = ref(false);
const rxName = ref(''); // 处方名称
const isInitial = (...args: unknown[]) => {
  const [value] = args;
  if (typeof value === 'boolean') {
    isInitialLoad.value = value;
  }
};
const prpops = defineProps({
  group: {
    type: Object,
    default: () => {},
  },
  visitStatus: {
    type: String,
    default: '1',
  },
  onZS: {
    type: Function,
    default: '',
  },
  weight: {
    type: Number,
    default: 0,
  },
  displayNowUUid2: {
    type: String,
    default: '',
  },
  recomScene: {
    type: String,
    default: '',
  },
});
const transfusionTableData = ref<any>({});
const displayNowUUid = ref('');
const onSearchKeyboard = (id: any) => {
  displayNowUUid.value = id;
  emits('searchKeyboard');
};
// 新增方法：生成提示信息
const generateTips = (row: any) => {
  ////console.log(row);

  const data1 = validateStorage(
    row.minPackQty,
    row.stockQty,
    row.minStockQty,
    row.totalOutQty,
    row.isSplit
  );
  ////console.log(data1);
  const tips: string[] = [];
  if (!data1 && row.totalOutQty) {
    tips.push('库存不足');
  }

  if (row?.usageList) {
    const usageList = row?.usageList.find(
      (item: any) => item.usageCode === row?.usageCode
    );
    ////console.log(usageList);
    if (usageList) {
      // const singleMin = (props?.weight * usageList.singleMin) / 50
      const singleMin = Math.round(
        ((prpops.weight ?? 50) * usageList.singleMin) / 50
      );
      const singleMax = Math.round(
        ((prpops.weight ?? 50) * usageList.singleMax) / 50
      );
      const dailyMax = Math.round(
        ((prpops.weight ?? 50) * usageList.dailyMax) / 50
      );
      const average = Math.round((singleMin + singleMax) / 2);

      if (row.dosage && row.dosage < singleMin) {
        tips.push('单次用量低于推荐单次最小用量');
      }
      if (row.dosage && row.dosage > singleMax) {
        tips.push('单次用量超过推荐单次最大用量');
      }
      if (row.frequencyCode) {
        const totalOutQty =
          getTimesPerDayFromCode(row.frequencyCode) * row.dosage;
        if (totalOutQty > dailyMax) {
          tips.push('单日用量超过推荐单日最大用量');
        }
      } else {
        const totalOutQty = row.frequencyTimes * row.dosage;
        if (totalOutQty > dailyMax) {
          tips.push('单日用量超过推荐单日最大用量');
        }
      }
    }
  }
  return tips;
};
const recalcTotalAmount = () => {
  // 新数据结构：groupList 下有 detailList，每个 detailList 里是药品
  const groupList =
    transfusionTableData.value &&
    Array.isArray(transfusionTableData.value.groupList)
      ? transfusionTableData.value.groupList
      : [];
  let sum = 0;
  for (const group of groupList) {
    if (!Array.isArray(group.detailList)) continue;
    for (const drug of group.detailList) {
      const qty = Number(drug.totalOutQty);
      const minPackQty = Number(drug.minPackQty);
      const price = Number(drug.price); // 分
      const splitPrice = Number(drug.splitPrice); // 分
      if (!qty || qty <= 0 || !minPackQty) continue;
      const { totalPrice } = calculateAll({
        totalOutQty: qty,
        dosage: drug.dosage,
        frequencyTimes: group.frequencyTimes,
        cycle: group.cycle,
        isMinSplit: drug.isMinSplit,
        minPackQty: minPackQty,
        isSplit: drug.isSplit,
        price: price,
        splitPrice: splitPrice,
      });
      sum += Number.isFinite(totalPrice) ? totalPrice : 0;
    }
  }
  ////console.log(sum, '---------------------');
  transfusionTableData.value.totalAmount = sum;
};
// 依据当前行、分组频率与周期，计算该行总量
const recalcRowTotal = (row: any) => {
  const cycleNum = Number(row?.cycle);
  const timesPerDay = row.frequencyTimes;
  const dosageNum = Number(row?.dosage);
  row.uuid = uuidv4();
  if (
    isNaN(dosageNum) ||
    dosageNum <= 0 ||
    isNaN(cycleNum) ||
    cycleNum <= 0 ||
    timesPerDay == null
  ) {
    return;
  }
  const newTotal = calculateTotalDose(
    dosageNum,
    timesPerDay,
    cycleNum,
    row.isMinSplit,
    row.isSplit,
    row.minPackQty
  );
  if (row.totalOutQty !== newTotal) {
    row.totalOutQty = newTotal;
  }
};
const displayNow = ref<any>({});
watch(
  () => prpops.group,
  (newValue) => {
    if (!newValue) {
      transfusionTableData.value = {};
      return;
    }
    isInitialLoad.value = true;
    displayNow.value = newValue;
    const processedGroupList =
      newValue.groupList && newValue.groupList.length > 0
        ? newValue.groupList.map((item: any) => {
            const detailList = Array.isArray(item.detailList)
              ? item.detailList.map((d: any) => ({ ...d, uuid: uuidv4() }))
              : [];
            const selectedFrequency = frequency.value?.find(
              (freq: { frequencyCode: any }) =>
                freq.frequencyCode === item.frequencyCode
            );
            item.frequencyTimes = selectedFrequency.frequencyTimes;

            return { ...item, uuid: uuidv4(), detailList };
          })
        : [];
    // 若数据无变化则跳过，避免递归更新
    const prev = transfusionTableData.value?.groupList || [];
    const same =
      Array.isArray(prev) &&
      Array.isArray(processedGroupList) &&
      prev.length === processedGroupList.length &&
      prev.every(
        (g: any, idx: number) => g.uuid === processedGroupList[idx].uuid
      );
    if (same) return;

    transfusionTableData.value = {
      ...newValue,
      groupList: processedGroupList,
      rxName: newValue.rxName,
      totalAmount: 0,
    };
    ////console.log(newValue, 'newValue');
    recalcTotalAmount();
  },
  { immediate: true }
);
const handleActiveTypeChange = (type: 'inspection' | 'examination') => {
  activeType.value = type;
  dialogVisible.value = true;
};
// 深度差异比较函数
function getDeepChanges(newObj: any[], oldObj: any[], path = '') {
  if (!oldObj) return [{ path, newValue: newObj }];

  if (Array.isArray(newObj)) {
    const changes: any[] = [];
    newObj.forEach((item, index) => {
      changes.push(...getDeepChanges(item, oldObj[index], `${path}[${index}]`));
    });
    return changes;
  }

  return newObj !== oldObj
    ? [{ path, oldValue: oldObj, newValue: newObj }]
    : [];
}
// 监听state数据变化，计算价格
watch(
  () =>
    (Array.isArray(transfusionTableData.value?.groupList)
      ? transfusionTableData.value.groupList
      : []
    ).flatMap((group: any) =>
      Array.isArray(group.detailList)
        ? group.detailList.map(
            (drug: {
              dosage: any;
              totalOutQty: any;
              price: any;
              splitPrice: any;
              minPackQty: any;
              uuid: any;
            }) => ({
              dosage: drug.dosage,
              totalOutQty: drug.totalOutQty,
              price: drug.price,
              splitPrice: drug.splitPrice,
              minPackQty: drug.minPackQty,
              cycle: group.cycle,
              frequencyTimes: group.frequencyTimes,
              uuid: group.uuid,
              uuidv2: drug.uuid,
            })
          )
        : []
    ),
  (nVal, cVal) => {
    //console.log('------------------', nVal);
    //console.log('1111111111111111111', cVal);
    if (nVal.length == 0) {
      return;
    }
    //console.log(getDeepChanges(nVal, cVal));

    const uuid = getDeepChanges(nVal, cVal)[
      getDeepChanges(nVal, cVal).length - 1
    ].newValue.uuid;
    const uuidv2 = getDeepChanges(nVal, cVal)[
      getDeepChanges(nVal, cVal).length - 1
    ].newValue.uuidv2;
    //console.log(uuid);

    // 先补全 totalOutQty
    if (transfusionTableData.value?.groupList.length == 0) {
      return;
    }
    for (const row of transfusionTableData.value?.groupList || []) {
      row.detailList.forEach((drug: any) => {
        drug.cycle = row.cycle;
        if (row.uuid == uuid || drug.uuidv2 == uuidv2) {
          // recalcRowTotal(drug);
          // row.tips = generateTips(row);
          // row.uuid = uuidv4();
          if (currentEditField.value != 'totalOutQty') {
            // recalcRowTotal(row);
          }
        }
      });
    }
    //console.log(transfusionTableData.value?.groupList);
    recalcTotalAmount();
  },
  { deep: true, immediate: true }
);
// 处理表格组件事件
// const updateTableData = (newData: InspectionItem[]) => {
//   ////console.log(newData, 'newData');
//   transfusionTableData.value.groupList = newData;
// };
// 处理表格组件事件
const updateTableData = (newData: InspectionItem[], tableData: any) => {
  ////console.log(newData, 'newData');
  tableData.detailList = newData;
  tableData.detailList.forEach((element: any) => {
    // 计算单行价格
    // recalcRowTotal(element);
    element.tips = generateTips(element);
  });
  // 计算总数
  recalcTotalAmount();
};
const onfrequencyfocus = () => {
  keyboardVisible.value = false;
  currentEditRow.value = null;
  showMedicationTabs.value = false;
  currentEditField.value = null;
};
const onSelect = (row: any, usage: any, usageName: any) => {
  ////console.log('usage', usage);
  ////console.log('currentUsageRow', currentUsageRow.value);
  row.usageCode = usage.value[0];
  row.usageCodeText = usageName;
  showMedicationTabs.value = false;
  transfusionTableData.value.groupList.forEach((element: any) => {
    element.usageCode = usage.value[0];
    element.usageCodeText = usageName;
    element.detailList.forEach((element: any) => {
      element.usageCode = usage.value[0];
      element.usageCodeText = usageName;
    });
  });
};
// 数字键盘相关方法
const showKeyboard = (row: any, index: number, field: any) => {
  currentEditRow.value = row;
  isCurrentEditRow.value = index;
  currentEditField.value = field;
  keyboardVisible.value = true;
};
const inputNumber = (num: string, type?: string) => {
  if (type) {
    // const currentValue = currentEditRow.value[currentEditField.value];
    currentEditRow.value[currentEditField.value] = Number(num);
    currentEditRow.value['detailList'].forEach((element: any) => {
      element.cycle = num;
      // recalcRowTotal(element);
    });
  } else {
    if (!currentEditRow.value || !currentEditField.value) {
      return;
    }
    // 获取当前值，如果不存在则使用默认值
    const currentValue = currentEditRow.value[currentEditField.value];
    if (currentValue === undefined || currentValue === null) {
      // 设置默认值
      currentEditRow.value[currentEditField.value] = parseInt(num);
      currentEditRow.value['detailList'].forEach((element: any) => {
        element.cycle = num;
        // recalcRowTotal(element);
      });
      return;
    }

    const currentValueStr = currentValue.toString();
    const newValue = parseInt(currentValueStr + num);

    const maxValue = currentEditField.value === 'cycle' ? 999 : 999;
    if (newValue <= maxValue) {
      currentEditRow.value[currentEditField.value] = newValue;
      currentEditRow.value['detailList'].forEach((element: any) => {
        element.cycle = newValue;
        // recalcRowTotal(element);
      });
      ////console.log(currentEditRow.value['detailList']);
    } else {
    }
  }
};

const deleteNumber = () => {
  if (!currentEditRow.value || !currentEditField.value) {
    ////console.log('deleteNumber: currentEditRow or currentEditField is null');
    return;
  }

  const currentValue = currentEditRow.value[currentEditField.value];
  if (currentValue === undefined || currentValue === null) {
    ////console.log('deleteNumber: current value is undefined/null');
    return;
  }

  const currentValueStr = currentValue.toString();
  const newValue = currentValueStr.slice(0, -1);
  currentEditRow.value[currentEditField.value] =
    newValue === '' ? null : parseInt(newValue);
};
const onUsageCode = (row: any) => {
  if (currentUsageRow.value === row && showMedicationTabs.value) {
    // 再次点击同一行则关闭
    showMedicationTabs.value = false;
    currentUsageRow.value = null;
  } else {
    showMedicationTabs.value = true;
    currentUsageRow.value = row;
  }
};
const toChineseNumber = (num: number) => {
  const cnNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  const cnUnits = ['', '十', '百', '千', '万'];
  if (num < 10) return cnNums[num];
  if (num < 20) return '十' + (num === 10 ? '' : cnNums[num % 10]);
  if (num < 100) {
    const ten = Math.floor(num / 10);
    const unit = num % 10;
    return cnNums[ten] + '十' + (unit === 0 ? '' : cnNums[unit]);
  }
  // 这里只处理到99，更多位数可扩展
  return num;
};
// 加一组
const addNewRow = (type: number, group?: any, index?: number) => {
  // type 1 添加分组内药品
  // type 2 在指定位置插入新分组
  if (type === 1 && group) {
    // 在分组内添加药品逻辑保持不变
    emits('addNewRow', transfusionTableData.value.groupList);
  } else if (type === 2) {
    const newGroup = {
      detailList: [],
      groupName: `第${toChineseNumber(
        transfusionTableData.value.groupList.length + 1
      )}组`,
      usageCode: 'JMDZ',
      usageCodeText: '静脉滴注',
      frequencyCode: 'qd',
      frequencyCodeText: '1天1次',
      frequencyTimes: 1,
      cycle: 1,
      cycleUnit: 'day',
      cycleUnitText: '天',
      ivDripRate: '50',
      subtotal: 1000,
      uuid: uuidv4(),
    };

    if (index === undefined || index < 0) {
      // 如果没有提供index或index无效，添加到末尾
      transfusionTableData.value.groupList.push(newGroup);
    } else {
      // 在指定index后插入新分组
      transfusionTableData.value.groupList.splice(index + 1, 0, newGroup);

      // 更新后续分组的组名（如果需要）
      transfusionTableData.value.groupList.forEach(
        (group: { groupName: string }, idx: number) => {
          group.groupName = `第${toChineseNumber(idx + 1)}组`;
        }
      );
    }
  }
};
// 基于枚举提供滴注速率自动补全
const queryIvDripRateSuggestions = (query: string, cb: any) => {
  const list = Array.isArray(infusionIvDripRateEnum.value)
    ? infusionIvDripRateEnum.value
    : [];
  const q = (query || '').toString().trim();
  const filtered = list
    .map((x: any) =>
      typeof x === 'string' ? { value: x } : { value: x?.value }
    )
    .filter((x: any) => x.value)
    .filter((x: any) => (q ? String(x.value).includes(q) : true));
  cb(list);
};
const onIvDripRateSelect = (row: any, item: any) => {
  const val = item?.value ?? '';
  row.ivDripRate = val;
  // 复用原有的变更逻辑（如需触发频率联动，可在此调用）
  // onFrequency(row); // 若不需要联动可注释
};
// 删除分组
const removeRow = (type: number, group: any) => {
  if (type === 2 && group) {
    const idx = transfusionTableData.value.groupList.indexOf(group);
    if (idx > -1) {
      transfusionTableData.value.groupList.splice(idx, 1);
      transfusionTableData.value.groupList.forEach(
        (element: any, index: any) => {
          element.groupName = `第${toChineseNumber(index + 1)}组`;
        }
      );
    }
  }
};
const removeRow_1 = (group: any) => {
  if (group) {
    emits('removeRow', transfusionTableData.value.groupList);
  }
};

const onFrequency = (row: any, frequencyCode: any) => {
  const selectedFrequency = frequency.value?.find(
    (freq: { frequencyCode: any }) => freq.frequencyCode === frequencyCode
  );
  ////console.log(selectedFrequency);

  if (selectedFrequency) {
    row.cycleUnit = selectedFrequency.cycleUnit;
    row.cycleUnitText = useBaseData.getEnumData(
      selectedFrequency.cycleUnit,
      'cycleUnitEnum'
    );
    row.frequencyTimes = selectedFrequency.frequencyTimes;
    row.detailList.forEach((element: any) => {
      element.frequencyTimes = selectedFrequency.frequencyTimes;
      // recalcRowTotal(element);
    });
  }
};
const updateRow = (tableData: any, row: any, index: number) => {
  // 将子组件回传的单行变更写入父组件的 tableData.detailList
  if (!tableData) return;
  if (!Array.isArray(tableData.detailList)) tableData.detailList = [];

  // 优先用 uuid 精确定位
  if (row && row.uuid) {
    const pos = tableData.detailList.findIndex(
      (d: any) => d?.uuid === row.uuid
    );
    if (pos !== -1) {
      tableData.detailList[pos] = {
        ...(tableData.detailList[pos] || {}),
        ...row,
      };
      return;
    }
  }
  // 兜底：用 index 覆盖/合并
  tableData.detailList[index] = {
    ...(tableData.detailList[index] || {}),
    ...row,
  };
};
// 从传入的频率项中获取每天用药次数 frequencyTimes
const getTimesPerDay = (row: { frequencyCode: any } | undefined) => {
  const code = row?.frequencyCode;
  if (!code) return null;
  const freqItem = (frequency.value || []).find(
    (f: any) => f.frequencyCode === code
  );
  const times = Number((freqItem as any)?.frequencyTimes);
  return isNaN(times) || times <= 0 ? null : times;
};
// 从频率代码获取每天次数
function getTimesPerDayFromCode(code: string): number {
  if (!code) return 0;
  const item = frequency.value?.find((f: any) => f.frequencyCode === code);
  return Number(item?.frequencyTimes) || 0;
}
// 选择药品
const onStorage = async (list: any) => {
  // displayNow.value.storageId = row.storageId;
  // displayNow.value.storageName = row.storageName;
  // displayNow.value.detailList = [];
  const drugIdList = list
    .map((item: { detailList: any[] }) =>
      item.detailList.map((detail) => detail.drugId)
    )
    .flat();

  // ////console.log(drugIds); // [14, ...]

  // const drugIdList = list.map((item: any) => item.drugId);
  const result = await getDrugRxList({
    drugIdList: drugIdList.join(','),
    storageId: transfusionTableData.value.storageId,
  });
  if (result?.code != '200') {
    //ElMessage.error(result?.msg);
    return;
  }

  // 根据需求，将result.data中的stockQty、minStockQty、stockWarningQty赋值给displayNow.value.detailList中相同drugId的项目
  if (result.data && Array.isArray(result.data)) {
    transfusionTableData.value.groupList.forEach(
      (group: { uuid: string; detailList: any[] }) => {
        group.detailList.forEach((item: any) => {
          const matchingItem = result.data.find(
            (dataItem: any) => dataItem.drugId === item.drugId
          );
          if (matchingItem) {
            item.stockQty = matchingItem.stockQty;
            item.minStockQty = matchingItem.minStockQty;
            item.stockWarningQty = matchingItem.stockWarningQty;
            item.uuid = uuidv4();
          }
        });
        group.uuid = uuidv4();
      }
    );
    // transfusionTableData.value.detailList.forEach((item: any) => {
    //   const matchingItem = result.data.find(
    //     (dataItem: any) => dataItem.drugId === item.drugId
    //   );
    //   if (matchingItem) {
    //     item.stockQty = matchingItem.stockQty;
    //     item.minStockQty = matchingItem.minStockQty;
    //     item.stockWarningQty = matchingItem.stockWarningQty;
    //     item.tips = generateTips(item);
    //   }
    // });
    ////console.log(transfusionTableData.value);
  }
};
const handleSearchResultSelect = (result: any, group?: any) => {
  // group 为当前分组对象
  if (!group) return;
  if (!group.detailList) group.detailList = [];
  result.uuid = uuidv4(); // 添加唯一标识
  result = {
    ...result,
    splitPrice: result.splitPrice ?? 0,
    isMinSplit: result.isMinSplit ?? false,
    isSplit: result.isSplit ?? false,
    dosage: result.dosage ?? 1,
    cycle: group.cycle ?? 1,
    tips: generateTips(result),
    frequencyTimes: group.frequencyTimes ?? 1,
    // 其它你需要的字段
  };
  // recalcRowTotal(result);
  ////console.log(result);

  group.detailList = [...group.detailList, result];
};
const hideKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.number-keyboard')) {
      return;
    }
  }
  keyboardVisible.value = false;
  currentEditRow.value = null;
  currentEditField.value = null;
};
// 点击其他地方关闭 MedicationTabs
const handleGlobalClick = (event: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.medication-tabs')) {
      return;
    }
  }
  showMedicationTabs.value = false;
  currentUsageRow.value = null;
};
onMounted(() => {
  const globalClickHandler = (event: Event) => {
    hideKeyboard(event);
    handleGlobalClick(event);
  };
  document.addEventListener('mousedown', globalClickHandler);
});

onUnmounted(() => {
  const globalClickHandler = (event: Event) => {
    hideKeyboard(event);
    handleGlobalClick(event);
  };
  document.removeEventListener('mousedown', globalClickHandler);
});
defineExpose({
  transfusionTableData,
});
</script>
<style lang="scss" scoped>
.external-treatment-container {
  border-radius: 8px;
  margin-bottom: 10px;
  border: 1px solid #e7e7e7;
  .external-treatment-prescription {
    border-radius: 8px;
  }
  .custom-table {
    width: 100%;
    background: #ffffff;

    .table-header {
      display: flex;
      padding: 12px 16px;
      background-color: #f8f8f8;
      border-bottom: 1px solid #e4e7ed;
      align-items: center;
      border-radius: 7px;
    }

    .prescription-form-row {
      display: flex;
      align-items: center;
      gap: 7px;

      .form-item {
        display: flex;
        align-items: center;
        position: relative;
        .unit-text {
          font-size: 14px;
          color: #333;
          margin-left: 4px;
        }
      }
    }

    .acupoint-selection-area {
      .acupoint-row {
        display: flex;
        align-items: center;
        gap: 12px;

        .combined-select-group {
          display: flex;
          align-items: center;
          box-shadow: 0 0 0 1px #dcdfe6;
          border-radius: 5px;
          position: relative;

          &:focus-within {
            box-shadow: 0 0 0 1px #409eff !important;
          }

          &:hover {
            box-shadow: 0 0 0 1px #c0c4cc !important;
          }

          .left-select {
            height: 100%;
            :deep(.el-input__wrapper) {
              border: none !important;
              border-radius: 0 !important;
              box-shadow: none !important;
              height: 38px;
            }

            :deep(.el-input__wrapper:focus) {
              box-shadow: none !important;
              border: none !important;
            }

            :deep(.el-input__wrapper:hover) {
              box-shadow: none !important;
              border: none !important;
            }
          }

          .right-select {
            height: 100%;
            :deep(.el-input__wrapper) {
              border: none !important;
              border-radius: 0 !important;
              box-shadow: none !important;
              height: 38px;
            }

            :deep(.el-input__wrapper:focus) {
              box-shadow: none !important;
              border: none !important;
            }

            :deep(.el-input__wrapper:hover) {
              box-shadow: none !important;
              border: none !important;
            }
          }

          .select-divider {
            width: 1px;
            height: 24px;
            background-color: #e4e7ed;
            flex-shrink: 0;
            margin: 0 2px;
          }

          &:hover {
            border-color: #c0c4cc;
          }

          &:focus-within {
            border-color: #409eff;
            /* 只显示右边线的方法 */
            box-shadow: inset -1px 0 0 0 rgba(64, 158, 255, 0.3);
          }
        }

        .acupoint-group {
          display: flex;
          align-items: center;
        }

        .remove-button {
          display: flex;
          align-items: center;
          margin-left: auto;
          margin-right: 12px;

          .remove-btn {
            padding: 4px;
            color: #c0c4cc;

            &:hover {
              color: #f56c6c;
            }
          }
        }

        .acupoint-selector {
          display: flex;
          align-items: center;
          gap: 8px;
          background: #ffffff;
          padding: 8px 12px;
          border-radius: 6px;
          border: 1px solid #e4e7ed;
          cursor: pointer;
          transition: all 0.2s;
          height: 51px;
          &:hover {
            background: #e9ecef;
            border-color: #409eff;
          }

          .selector-text {
            font-size: 14px;
            color: #666;
          }

          .selector-icon {
            color: #f56c6c;
          }
        }
      }
    }
  }

  // 无边框选择框样式
  :deep(.borderless-select) {
    .el-input__wrapper {
      border: 1px solid #dcdfe6;
      box-shadow: none;
      border-radius: 6px;
      height: 36px !important;
    }

    &:hover .el-input__wrapper {
      border-color: #c0c4cc;
    }

    &.is-focus .el-input__wrapper {
      border-color: #409eff;
    }

    .el-input__suffix {
      .el-input__suffix-inner {
        .el-icon {
          color: #909399;
        }
      }
    }
  }

  // 无边框输入框样式
  :deep(.borderless-input) {
    .el-input__wrapper {
      border: 1px solid #dcdfe6;
      box-shadow: none;
      border-radius: 6px;
    }

    &:hover .el-input__wrapper {
      border-color: #c0c4cc;
    }

    &.is-focus .el-input__wrapper {
      border-color: #409eff;
    }
  }
}

.header-cell {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #333333;

  .delete-icon {
    color: #c0c4cc;
    cursor: pointer;

    &:hover {
      color: #f56c6c;
    }
  }
}
// 数字键盘样式
.number-keyboard {
  position: absolute;
  top: 60%;
  left: 0;
  z-index: 9999 !important;
  border-radius: 8px;
  padding: 8px;
  margin-top: 4px;
  transform: translateZ(0); // 硬件加速，确保显示在最顶层

  .keyboard-row {
    display: flex;
    gap: 4px;
    margin-bottom: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    width: 50px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #f8f9fa;
    color: #333;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      width: 104px; // 退格键宽度是两个按钮+间距
      background: #f56c6c;
      color: white;
      font-size: 14px;

      &:hover {
        background: #f78989;
      }
    }
  }
}
</style>
<style lang="scss">
.left-select {
  .el-select__wrapper {
    height: 51px;
    background-color: rgba(220, 220, 220, 0.1) !important;
    box-shadow: inset -1px 0 0 0 #dcdfe6;
  }
  .el-select__wrapper:hover {
    box-shadow: inset -1px 0 0 0 #dcdfe6 !important;
  }
  .el-select__wrapper:focus-within {
    border-color: #409eff;
    box-shadow: inset -1px 0 0 0 rgba(64, 158, 255, 0.3);
  }
}
.right-select {
  .el-select__wrapper {
    height: 51px;
    box-shadow: none !important;
  }
  .el-select__wrapper:hover {
    box-shadow: none !important;
  }
  .el-select__wrapper:focus-within {
    box-shadow: none !important;
    border: none !important;
  }
}
.borderless-select_1 {
  .el-select__wrapper {
    height: 36px !important;
  }
}
</style>
